package com.life.wang.controller;

import com.life.wang.pojo.TbUser;
import com.life.wang.pojo.vo.User;
import com.life.wang.service.UserService;
import com.life.wang.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/findAll")
    public List<TbUser> findAll() {
        return userService.findAll();
    }

    @RequestMapping("/login")
    public Result login(@RequestBody TbUser user){
        try{
            User _user = userService.login(user.getUsername(),user.getPassword());
            if(null == _user){
                return new Result(false,"登录失败，请检查用户名或密码是否正确！");
            }else{
                return new Result(true,"登录成功",_user);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"登录错误");
        }
    }

    @RequestMapping("/register")
    public Result register(@RequestBody TbUser user){
        try {
            userService.register(user);
            return new Result(true,"注册成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,e.getMessage());
        }
    }

    @RequestMapping("/upload")
    public Result upload(MultipartFile file,String userid){
        try{
            User user = userService.upload(file,userid);
            if(null == user){
                return new Result(false,"上传失败！");
            }else{
                return new Result(true,"上传成功",user);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"上传失败！");
        }
    }

}
